package com.example.vote.flow.interceptor;

import cn.hutool.json.JSONUtil;
import com.example.vote.flow.pojo.core.Principle;
import com.example.vote.flow.web.JsonResult;
import com.example.vote.flow.web.StateCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断Session信息表示的用户是否是管理员
        HttpSession session = request.getSession();
        Principle principle = (Principle) session.getAttribute(Principle.SESSION_KEY);
        if (principle.getIsAdmin() != 1) {
            String message = "无此访问权限！";
            JsonResult jsonResult = JsonResult.fail(StateCode.ERROR_FORBIDDEN, message);

            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(jsonResult));
            writer.close();
            return false;
        }
        return true;
    }

}
